package util;
import javafx.scene.CustomNode;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.effect.PerspectiveTransform;
import javafx.util.Math;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;

public class FlipView extends CustomNode {
    public var frontNode:Maze;
    public var backNode:Node;

    var flipped = false;
    var time = Math.PI/2;

    var width:Number;
    var height:Number;
    var backVisible = false;

    public var anim = Timeline {
        keyFrames: [
            at(0s) { time=> Math.PI/2 tween Interpolator.EASEBOTH},
            at(0.5s) { time=> 0 },
            KeyFrame { time: 501ms, values: time => Math.PI , action: function() {backVisible = not backVisible}},

            at(1s) { time => Math.PI/2 tween Interpolator.EASEBOTH},
            KeyFrame { time: 1.0s action: function() { flipped = not flipped; } }
        ]
    }

    override public function create():Node {
        width = frontNode.boundsInLocal.width;
        height = frontNode.boundsInLocal.height;
        return Group {
            content: [
                Group { content: backNode visible: bind backVisible effect: bind getPT(time) },
                Group { content: frontNode  visible: bind not backVisible effect: bind getPT(time) },
            ]
        }
    }

    function getPT(t:Number):PerspectiveTransform {
        var radius = width/2;
        var back = height/10;
        return PerspectiveTransform {
            ulx: radius - Math.sin(t)*radius     uly: 0 - Math.cos(t)*back
            urx: radius + Math.sin(t)*radius     ury: 0 + Math.cos(t)*back
            lrx: radius + Math.sin(t)*radius     lry: height - Math.cos(t)*back
            llx: radius - Math.sin(t)*radius     lly: height + Math.cos(t)*back
        }
    }

    public function doFlip() {
        if(flipped) {
            anim.rate = -1.0;
            anim.time = 1s;
        } else {
            anim.rate = 1.0;
            anim.time = 0s;
        }
        anim.play();
    }

}
